// pages/device/autowater.js
const global = getApp().globalData
import {
  getDeviceProperties,
  sendCmd
} from '../../utils/api.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    device_name: '',
    device_id: '',
    result_code: '...'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      device_id: options.deviceId || wx.getStorageSync('device_id'),
      device_name: options.dname
    })
    wx.setStorageSync('device_id', options.deviceId)
    this.getProperties();
  },
  getProperties: function () {
    getDeviceProperties({
      'project_id': global.project_id || wx.getStorageSync('project_id'),
      'device_id': this.data.device_id || wx.getStorageSync('device_id')
    }).then(res => {
      wx.stopPullDownRefresh({
        success: (res) => {},
      })
      this.setData({
        property: res.shadow[0].reported.properties
      })
      // {
      //   "device_id": "60d1d4795f880902bcb0652f_20210625204128rdmWbk",
      //   "shadow": [
      //    {
      //     "service_id": "AutoWater",
      //     "desired": {
      //      "properties": null,
      //      "event_time": null
      //     },
      //     "reported": {
      //      "properties": {
      //       "Soil_Moisture": 8,
      //       "Temperature": 28,
      //       "Humidity": 66,
      //       "MotorStatus": "OFF"
      //      },
      //      "event_time": "20210627T093851Z"
      //     },
      //     "version": 5755
      //    }
      //   ]
      //  }
    })
  },
  watering: function () {
    this.setData({
      result_code: '...'
    })
    var data = {
      "project_id": global.project_id,
      "device_id": this.data.device_id,
      "service_id": "AutoWater",
      "command_name": "AutoWater_Control_Pump",
      "paras": {
        "Motor": "ON"
      }
    }
    sendCmd(data).then(res => {
      console.log(res);
      this.setData({
        result_code: res.error_code || '成功'
      })
    }, err => {
      console.log(err);
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getProperties()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 返回
  back() {
    wx.switchTab({
      url: '/pages/home/index'
    })
  }
})